//
//  XJCommunityIWantServeController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/31.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  社区--我要服务

#import "XJCommunityIWantServeController.h"

//VC
#import "XJCommunityServeTypeViewController.h" // 服务类别
#import "XJCommunityHistoryViewController.h"


//View
#import "XJCommunityIwantServeCell.h"
#import "XJServeTypeModel.h"
#import "XJCommunityIWantServeSuccessView.h"
#import "XJIWantServiceFooterView.h" //footerView(描述+选择图片)

#import <AVFoundation/AVFoundation.h>
//vendor
#import <TZImagePickerController.h>
#import <QiniuSDK.h>

@interface XJCommunityIWantServeController ()<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate>
// 界面用tableView来做。tableView cell + tableVeiw表尾 + 最底部一个按钮(提交)
{
    NSString *_qiniuToken; //七牛上传图片token。
}
/**七牛云返回的图片url数组*/
@property (nonatomic, strong) NSMutableArray *qiniuImagesUrlArr;

@property(nonatomic, strong)UITableView *tableView;

@property(nonatomic, copy) NSArray *dataArray;
@property(nonatomic, strong) UIView *bottomSubmitView; //提交veiw
@property(nonatomic, strong) XJCommunityIWantServeSuccessView *successView;


// 单独记录cell的输入内容
@property(nonatomic, strong) NSString *serveTypeStr;
/**2.服务名称*/
@property (nonatomic, copy) NSString *serveName;
/**2-2服务id*/
@property (nonatomic, copy) NSString *serveId;
/**3.联系人称呼*/
@property (nonatomic, copy) NSString *personName;
/**4.联系电话*/
@property (nonatomic, copy) NSString *phoneNum;
/**5.描述*/
@property (nonatomic, copy) NSString *descStr;
@property (nonatomic, strong) XJIWantServiceFooterView *footerView;

/**目的:用于调取系统相机进行拍照 7-17 */
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
/**选择的image数组*/
@property (nonatomic, strong) NSMutableArray *selectImgArray;
@end

@implementation XJCommunityIWantServeController

#pragma mark - 一生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupNav];
    
    [self requestData];
    [self requestQiNiuToken];
    
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = self.footerView;
    
    [self.view addSubview:self.bottomSubmitView];
    
    [self.view addSubview:self.successView];
    self.successView.hidden = YES; // 默认隐藏。请求成功在显示。
}

- (void)requestData {
    self.dataArray = @[@"服务类别",@"服务名称",@"联系人称呼",@"联系人电话"];
    
}
- (void)setupNav {
    self.navTitle = @"我要服务";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"记录" style:(UIBarButtonItemStylePlain) target:self action:@selector(recordAction)];
}
#pragma mark - 1-2 记录
- (void)recordAction {
    XJLog(@"点击-----》记录 社区id:%@",self.community_id);
    if ([NSString isEmptyString:self.community_id]) {
        XJLog(@"community_id 不能为空");
        return;
    }
    
    XJCommunityHistoryViewController *communityVC = [[XJCommunityHistoryViewController alloc] init];
    communityVC.communityId = self.community_id;
    

    [self.navigationController pushViewController:communityVC animated:YES];
}
#pragma mark - lazy
- (NSMutableArray *)qiniuImagesUrlArr {
    if (!_qiniuImagesUrlArr) {
        _qiniuImagesUrlArr = [NSMutableArray array];
    }
    return _qiniuImagesUrlArr;
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - XJTopNavH - 60) style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        [_tableView registerClass:[XJCommunityIwantServeCell class] forCellReuseIdentifier:@"XJCommunityIwantServeCellId"];
        
        
        // 作用:点击tableview空白处回收键盘
        // https://blog.csdn.net/qin_xiaogang/article/details/51900308
        // https://www.jianshu.com/p/ce2594da8b54
        UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTableViewTouchInSide)];
        tableViewGesture.numberOfTapsRequired = 1;
        tableViewGesture.cancelsTouchesInView = NO;
        [_tableView addGestureRecognizer:tableViewGesture];
    }
    return _tableView;
}


- (XJCommunityIWantServeSuccessView *)successView {
    if (!_successView) {
        _successView = [[XJCommunityIWantServeSuccessView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - XJTopNavH)];
        
        XJWeakSelf(self)
        _successView.backButtonBlock = ^{
            [weakself.navigationController popViewControllerAnimated:YES];
        };
        
        // 继续提交
        _successView.goOnButtonBlock = ^{
            weakself.successView.hidden = YES;
        };
    }
    return _successView;
}


- (UIView *)bottomSubmitView {
    if (!_bottomSubmitView) {
        //记住要减去导航条的高度 64 / 88
        _bottomSubmitView = [[UIView alloc] initWithFrame:CGRectMake(0, KHeight - XJTopNavH - 60, KWidth, 60)];
        _bottomSubmitView.backgroundColor = [UIColor whiteColor];
        
        
        CGFloat kbtn_x = 50;
        CGFloat kbtn_W = KWidth - kbtn_x*2;
        CGFloat kbtn_H = 40;
        CGFloat kbtn_y = (60 - kbtn_H)/2;
        
        
        // 提交按钮
        UIButton *submitButton = [UIButton buttonWithFrame:CGRectMake(kbtn_x, kbtn_y, kbtn_W, kbtn_H) target:self action:@selector(submitButtonAction) bgc:XJCOLOR_RGB(255, 218, 67) title:@"提交"];
        [_bottomSubmitView addSubview:submitButton];
        
    }
    return _bottomSubmitView;
}

- (XJIWantServiceFooterView *)footerView {
    if (!_footerView) {
        _footerView = [[XJIWantServiceFooterView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 320)];
        
        XJWeakSelf(self);
        //if imgArr.count < 6 点击最后一个item添加图片的回调。
        _footerView.xjiwsfooterClickLastItemToAddImgBlock = ^{
            [weakself rb_showSelectUpLoadImageTypeAlert];
        };
        
        
        _footerView.xjiwsfooterClickdeleteImgBlock = ^(NSIndexPath *indexPath) {
            XJLog(@"点击的indexPath是:%ld",indexPath.row);
            [weakself.selectImgArray removeObjectAtIndex:indexPath.item];
            weakself.footerView.xjIwsImgArr = weakself.selectImgArray; //重新赋值.不然步骤setter方法导致无法刷新。
            //同时删除对应图片url
            [weakself.qiniuImagesUrlArr removeObjectAtIndex:indexPath.item];
        };
    }
    return _footerView;
}

- (NSMutableArray *)selectImgArray {
    if (!_selectImgArray) {
        _selectImgArray = [NSMutableArray array];
    }
    return _selectImgArray;
}


#pragma mark - 提交 请求接口
- (void)submitButtonAction{
    XJLog(@"点击---》提交");
    
    NSLog(@"%@--%@--%@",self.serveName,self.personName,self.phoneNum);
    
    if ([NSString isEmptyString:self.serveTypeStr]) {
        [JRToast showWithText:@"请选择服务类别"];
        return;
    }
    if ([NSString isEmptyString:self.serveName]) {
        [JRToast showWithText:@"请输入服务名称"];
        return;
    }
    if ([NSString isEmptyString:self.personName]) {
        [JRToast showWithText:@"请输入联系人名称"];
        return;
    }
    if ([NSString isEmptyString:self.phoneNum]) {
        [JRToast showWithText:@"请输入联系人电话"];
        return;
    }
    
    if ([NSString isEmptyString:self.descStr]) {
        [JRToast showWithText:@"请输入描述内容"];
        return;
    }
    
    if ([NSString isEmptyString:self.serveId]) {
        XJLog(@"服务id不能为空");
        return;
    }
    if ([NSString isEmptyString:self.community_id]) {
        XJLog(@"社区id不能为空");
        return;
    }
    NSMutableDictionary *dicM =@{@"community_id":self.community_id,
                                 @"category_id":self.serveId,
                                 @"service_name":self.serveName,
                                 @"linkman":self.personName,
                                 @"phone":self.phoneNum,
                                 @"content":self.descStr
                                 }.mutableCopy;

    NSString *imgUrls = [self assembleImgUrlsWithQiNiuImgUrlArr:self.qiniuImagesUrlArr];
    if (![NSString isEmptyString:imgUrls]) { //如果有图就传。
        dicM[@"images"] = imgUrls;
    }
    
    // 调用接口
  
    XJLog(@"社区提交服务参数--->:%@",dicM);
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [XJHttpTool requestCommunitySubmitServeDic:dicM successH:^(id responseObjc) {
//        XJLog(@"成功:%@",responseObjc);
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([code isEqualToString:@"0"]) {
            [MBProgressHUD showSuccess:responseObjc[@"data"]];
            
            self.successView.hidden = NO; // 显示
        }else{
            [MBProgressHUD showError:responseObjc[@"message"]];
        }
                          
    } failH:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        [MBProgressHUD showError:[error localizedDescription]];
    }];

}

#pragma mark - 二 - 1UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellId"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"UITableViewCellId"];
        }
        
        cell.textLabel.text = self.dataArray[indexPath.row];
        cell.detailTextLabel.text = self.serveTypeStr;
        
        return cell;
    }else{
        XJCommunityIwantServeCell *iWantCell = [tableView dequeueReusableCellWithIdentifier:@"XJCommunityIwantServeCellId"];
        
        [iWantCell configureLeftLabelStr:self.dataArray[indexPath.row] rightTfStr:nil];
        
        iWantCell.serveCellBlock = ^(NSString *str) {
            if (indexPath.row == 1) {
                self.serveName = str;
            }else if (indexPath.row == 2){
                self.personName = str;
            }else if(indexPath.row == 3){
                self.phoneNum = str;
            }else {
                XJLog(@"未知");
            }
        };
        return iWantCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        
        XJCommunityServeTypeViewController *serveTypeVC = [[XJCommunityServeTypeViewController alloc] init];
        
        XJWeakSelf(self)
        serveTypeVC.selectServeTypeBlock = ^(XJServeTypeModel *typeModel) {
            XJLog(@"=====:%@",typeModel.serveId);
            weakself.serveTypeStr = typeModel.name;
            weakself.serveId = typeModel.serveId;

            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
        };
        
        [self.navigationController pushViewController:serveTypeVC animated:YES];
    }
}

//#pragma mark - SectionFooterView 描述
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    UIView *secFoooterV = [[UIView alloc] init];
//    CGFloat kLeft = ADAPTWidth(15);
//
//    UITextField *descTF = [[UITextField alloc] initWithFrame:CGRectMake(kLeft, 0, KWidth - kLeft, ADAPTHeight(50))];
//    descTF.placeholder = @"描述";
//    [descTF addTarget:self action:@selector(descTFAction:) forControlEvents:(UIControlEventEditingChanged)];
//    [secFoooterV addSubview:descTF];
//    return secFoooterV;
//}

//
//- (void)descTFAction:(UITextField *)tf {
//    if ([NSString isEmptyString:tf.text]) {
//        return;
//    }
//
//    self.descStr = tf.text;
//    XJLog(@"输入内容是:%@",tf.text);
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//
////    return ADAPTHeight(50);
//    return 1;
//}

#pragma mark - 四 选择图片相关
/**选择上传方式:拍照、从相册中选择*/
- (void)rb_showSelectUpLoadImageTypeAlert {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"请选择上传方式" preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *takPicAction = [UIAlertAction actionWithTitle:@"拍照上传" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self configureTzImagePickerVc];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    
    [alertVC addAction:takPicAction];
    [alertVC addAction:albumAction];
    [alertVC addAction:cancelAction];

    [self presentViewController:alertVC animated:YES completion:nil];
}


#pragma mark - 五 相机相册相关
/// 注意:这里拍照后不保存到本地相册中。
/// 从相册中选择照片
- (void)configureTzImagePickerVc {
    TZImagePickerController *tzIImgpickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    [self presentViewController:tzIImgpickerVc animated:YES completion:nil];
}
//选照片后会走 的代理方法 TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
//
    if(_qiniuToken.length < 1 ) {
        XJLog(@"获取七牛云token失败 无法上传");
        return;
    }
//
    //选择的图片是
    UIImage *image = [photos lastObject]; // 要取最后一个.取第一个的话每次取出来的都一样

    [self.selectImgArray addObject:image];
    self.footerView.xjIwsImgArr = self.selectImgArray;
    
    
//    //上传图片
    [self qiNiuUploadImage:image complete:^(NSString *imgUrl) {

        [self.qiniuImagesUrlArr addObject:imgUrl];
    }];
}


/// 获取相机权限
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        
        NSLog(@"没有相机权限  请在iPhone的""设置-隐私-相机""中允许访问相机");
        
    }else if(authStatus == AVAuthorizationStatusNotDetermined) {
        //如果首次拍照拒绝授权是相机也黑屏情况
        
        NSLog(@"==========");
        //请求获取相机权限
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
    }else {
        NSLog(@"不要那么多功能");
        
        [self pushImagePickerController];
    }
}


/// 弹出相机进行拍照
- (void)pushImagePickerController {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])) {
        self.imagePickerVc.sourceType = sourceType;
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
        
    }else {
        NSLog(@"模拟器无法打开");
    }
}


/// 使用拍摄的图片的代理回调
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //    NSLog(@"选择了图片:%@",info);
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        XJLog(@"拍照的图片是:%@",image);
        
        // 在这里进行上传图片
        [self qiNiuUploadImage:image complete:^(NSString *imgUrl) {
            [self.qiniuImagesUrlArr addObject:imgUrl];
        }];
    }
}

/// 关闭相机的代理回调
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    NSLog(@"取消相机");
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - 六 网络请求
- (void)requestQiNiuToken {
    
    [XJHttpTool requestQiNiuTokenSuccessH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            _qiniuToken = responseObjc[@"data"][@"token"];
        }
    } fialH:^(NSError *error) {
        XJLog(@"获取七牛云token失败:%@",error);
    }];
}
#pragma mark - 七 调用七牛云SDK进行图片上传
/**调用七牛云SDK进行图片上传*/
- (void)qiNiuUploadImage:(UIImage *)image complete:(void(^)(NSString *imgUrl))completeBlock {
    
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *imgName = [NSString stringWithFormat:@"%@.jpg",[self imgNameWithCuttentTime]];
    
    [upManager putData:imageData key:imgName token:_qiniuToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        //通过block将七牛返回的结果回调出去
        NSString *imgUrl = resp[@"url"];
        if (completeBlock) {
            completeBlock(imgUrl);
        }
        
    } option:nil];
}

#pragma mark - 八 Private method
/// 将当前系统时间作为图片的名字
- (NSString *)imgNameWithCuttentTime {
    NSDate *date = [NSDate date];
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyyMMddHHmmss";
    NSString *currentTimeStr = [fmt stringFromDate:date];
    
    return currentTimeStr;
}

/// 将图片url数组转换为字符串
- (NSString *)assembleImgUrlsWithQiNiuImgUrlArr:(NSMutableArray *)arr {
    NSMutableString *resultStr = [NSMutableString string];
    if (arr.count == 0) return nil;
    
    for (NSString *url in arr) {
        [resultStr appendFormat:@"%@,",url];
    }
    
    return [resultStr copy];
}


#pragma mark - TableView 点击空白处回收键盘
- (void)commentTableViewTouchInSide {
    XJLog(@"回收键盘");
    [self.tableView endEditing:YES];
}

@end
